package console

import (
	"fmt"
	"github.com/mitchellh/go-homedir"
	"golang.org/x/crypto/ssh"
	"io/ioutil"
	"log"
	"time"
)
import "os/exec"

func Exec1() {
	// 创建一个Cmd结构体
	cmd := exec.Command("ls", "-l", "/app")
	// // 不需要cmd.Run()
	out, err := cmd.Output()
	if err != nil {
		fmt.Println("执行命令出错: ", err)
		return
	} else {
		fmt.Println("获取命令执行结果: \n", string(out))
	}
}

// 机器平台信息
type Machine struct {
	IP       string
	Port     int
	Username string
	Password string
	Type     string
	KeyPath  string
}

func Login(m *Machine) *ssh.Client {

	//创建sshp登陆配置
	config := &ssh.ClientConfig{
		Timeout:         3 * time.Second, //ssh 连接time out 时间一秒钟, 如果ssh验证错误 会在一秒内返回，尽量短些
		User:            m.Username,
		HostKeyCallback: ssh.InsecureIgnoreHostKey(), //这个可以, 但是不够安全
		//HostKeyCallback: hostKeyCallBackFunc(h.Host),
	}
	if m.Type == "password" {
		config.Auth = []ssh.AuthMethod{ssh.Password(m.Password)}
	} else {
		config.Auth = []ssh.AuthMethod{publicKeyAuthFunc(m.KeyPath)}
	}

	//dial 获取ssh client
	addr := fmt.Sprintf("%s:%d", m.IP, m.Port)
	client, err := ssh.Dial("tcp", addr, config)
	if err != nil {
		log.Fatal("创建ssh client 失败：\n", err)
	}
	return client
}

func Demo() {
	sshHost := "10.135.34.114"
	sshUser := "appuser"
	sshPassword := "ECSB&openapi2023"
	sshType := "password" //password 或者 key
	sshKeyPath := ""      //在服务器生成keyFile"
	sshPort := 22

	//创建sshp登陆配置
	config := &ssh.ClientConfig{
		Timeout:         3 * time.Second, //ssh 连接time out 时间一秒钟, 如果ssh验证错误 会在一秒内返回，尽量短些
		User:            sshUser,
		HostKeyCallback: ssh.InsecureIgnoreHostKey(), //这个可以, 但是不够安全
		//HostKeyCallback: hostKeyCallBackFunc(h.Host),
	}
	if sshType == "password" {
		config.Auth = []ssh.AuthMethod{ssh.Password(sshPassword)}
	} else {
		config.Auth = []ssh.AuthMethod{publicKeyAuthFunc(sshKeyPath)}
	}

	//dial 获取ssh client
	addr := fmt.Sprintf("%s:%d", sshHost, sshPort)
	sshClient, err := ssh.Dial("tcp", addr, config)
	if err != nil {
		log.Fatal("创建ssh client 失败：\n", err)
	}
	defer sshClient.Close()

	//创建ssh-session
	session, err := sshClient.NewSession()
	if err != nil {
		log.Fatal("创建ssh session 失败", err)
	}
	defer session.Close()
	//执行远程命令
	combo, err := session.CombinedOutput("ls -la /app")
	if err != nil {
		log.Fatal("远程执行cmd 失败", err)
	}
	log.Println("命令输出:", string(combo))

}

// 读取文件的方法
func publicKeyAuthFunc(kPath string) ssh.AuthMethod {
	keyPath, err := homedir.Expand(kPath)
	if err != nil {
		log.Fatal("find key's home dir failed", err)
	}
	key, err := ioutil.ReadFile(keyPath)
	if err != nil {
		log.Fatal("ssh key file read failed", err)
	}
	// Create the Signer for this private key.
	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		log.Fatal("ssh key signer failed", err)
	}
	return ssh.PublicKeys(signer)
}
